package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.dto.AdvDTO;
import info.batcloud.fanli.core.dto.AdvSpaceItemDTO;
import info.batcloud.fanli.core.entity.AdvSpaceItem;
import info.batcloud.fanli.core.repository.AdvSpaceItemRepository;
import info.batcloud.fanli.core.service.AdvService;
import info.batcloud.fanli.core.service.AdvSpaceItemService;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdvSpaceItemServiceImpl implements AdvSpaceItemService {

    @Inject
    private AdvSpaceItemRepository advSpaceItemRepository;

    @Inject
    private AdvService advService;

    @Override
    public void add(AdvSpaceItemAddParam param) {
        int idx = advSpaceItemRepository.countByAdvSpaceId(param.getAdvSpaceId());
        for (Long id : param.getAdvIdList()) {
            AdvSpaceItem adi = new AdvSpaceItem();
            adi.setAdvId(id);
            adi.setAdvSpaceId(param.getAdvSpaceId());
            adi.setIdx(idx++);
            advSpaceItemRepository.save(adi);
        }
    }

    @Override
    public void deleteById(long id) {
        advSpaceItemRepository.delete(id);
    }

    @Override
    public List<AdvSpaceItemDTO> findByAdvSpaceId(long advSpaceId) {
        List<AdvSpaceItem> advSpaceItems = advSpaceItemRepository.findByAdvSpaceId(advSpaceId);
        List<AdvSpaceItemDTO> advSpaceItemDTOList = new ArrayList<>();
        Map<Long, AdvDTO> map = new HashMap<>();
        List<Long> advIds = advSpaceItems.stream().map(o -> o.getAdvId()).collect(Collectors.toList());
        List<AdvDTO> advDTOList = advService.findValidByIds(advIds);
        for (AdvDTO advDTO : advDTOList) {
            map.put(advDTO.getId(), advDTO);
        }
        List<AdvSpaceItemDTO> list = new ArrayList<>();
        for (AdvSpaceItem advSpaceItem : advSpaceItems) {
            if(!map.containsKey(advSpaceItem.getAdvId())) {
                continue;
            }
            AdvSpaceItemDTO bo = new AdvSpaceItemDTO();
            advSpaceItemDTOList.add(bo);
            bo.setId(advSpaceItem.getId());
            bo.setAdv(map.get(advSpaceItem.getAdvId()));
            list.add(bo);
        }
        return advSpaceItemDTOList;
    }
}
